import Vue from 'vue'
import Vuex from 'vuex'
//导入包
import createPersistedState from "vuex-persistedstate";
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  //配置vuex的插件
  plugins: [createPersistedState()],
  state: {
    //存储token
    token: "",
    //存储userInfo
    userInfo:{}
  },
  getters: {},
  mutations: {
    updateToken(state, newtoken) {
      state.token = newtoken;
    },
    //定义更新userINfo的函数
    updateUserInfo(state, info) {
      state.userInfo = info
    }
  },
  actions: {
    //定义发送请求，获取用户信息数据
    async initUserInfo(context) {
      //context:是store的实例对象
      console.log(context)
      const { data: res } = await axios.get('/my/userinfo', {
        headers: {
          Authorization:context.state.token
        }
      })
      console.log(res)
      if (res.code === 0) {
        //将获取到的数据保存到vuex中 res.data
        context.commit('updateUserInfo',res.data)
      }
    }
  },
  modules: {},
});
